import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    username: '',
    role: '',
    token: null
  }),
  
  actions: {
    async login(loginForm) {
      try {
        const response = await fetch('/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(loginForm),
        });

        if (!response.ok) {
          throw new Error('Login failed');
        }

        const data = await response.json();
        this.username = data.username; // 注意拼写是 username
        this.role = data.role;
        this.token = data.token;
      } catch (error) {
        console.error('Login error:', error);
        // 处理错误，例如显示提示信息
      }
    },
    
    logout() {
      this.token = null;
      this.username = '';
      this.role = '';
    }
  }
});